package com.mh.dto.bo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mh.dto.vo.MessageOut;
import com.mh.dto.vo.MessageReceive;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * Date:2024/11/14
 * author:zmh
 * description: 用户管理器单例对象
 **/

@Data
@Component
@Slf4j
public class UserManager {
    // 管理连接用户信息
    private final HashMap<String, WebSocketSession> userMap = new HashMap<>();

    // 加入用户
    public void addUser(String userId, WebSocketSession session) {
        userMap.put(userId, session);
        log.info("用户{}加入",  userId);
    }

    // 移除用户
    public void removeUser(String userId) {
        userMap.remove(userId);
        log.info("用户{}退出", userId);
    }

    // 获取用户
    public WebSocketSession getUser(String userId) {
        return userMap.get(userId);
    }

    // 获取所有用户ID构造成list返回
    public List<String> getAllUserId() {
        return userMap.keySet().stream().toList();
    }

    // 通知用户加入-广播消息
    public void sendMessageAllUser() throws IOException {
        // 获取所有连接用户ID列表
        List<String> allUserId = getAllUserId();
        for (String userId : userMap.keySet()) {
            WebSocketSession session = userMap.get(userId);
            MessageOut messageOut = new MessageOut("join", allUserId);
            String messageText = new ObjectMapper().writeValueAsString(messageOut);
            // 广播消息
             session.sendMessage(new TextMessage(messageText));
        }
    }

    // 给指定用户发送特定类型消息
    public void sendMessage(MessageReceive messageReceive){
        String userId = messageReceive.getUserId();
        String type = messageReceive.getType();
        Object data = messageReceive.getData();
        WebSocketSession session = getUser(userId);
        try {
            MessageOut messageOut = new MessageOut(type, data);
            String messageText = new ObjectMapper().writeValueAsString(messageOut);
            session.sendMessage(new TextMessage(messageText));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
